//
//  OpenSDK_LoginMailView.m
//  OpenSDK
//
//  Created by 涂俊 on 2018/7/20.
//  Copyright © 2018年 WYHT. All rights reserved.
//

#import "OpenSDK_LoginMailView.h"
#import "OpenSDK_LoginLoadingView.h"
#import "OpenSDK_Toast.h"
#import "OpenSDK_UIManager.h"
#import "OpenSDK_LoginManager.h"
#import "OpenSDK_DataManager.h"
#import "OpenSDK_DataKeys.h"
#import "OpenSDK_UIUtil.h"
#import "OpenSDK_UserAgreementView.h"
#import "OPKWebViewController.h"
#import "OPKTracking.h"
#import "OPKCoreConfiguration.h"

@interface OpenSDK_LoginMailView ()<UITextFieldDelegate>
@property (unsafe_unretained, nonatomic) IBOutlet OpenSDK_UserAgreementView *userAgreementView;
@property (unsafe_unretained, nonatomic) IBOutlet NSLayoutConstraint *contentHeightConstraint;


@end

@implementation OpenSDK_LoginMailView

{
    BOOL showPassword;
}

#pragma mark - 生命周期函数
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    _bgView.backgroundColor = UIColor.whiteColor;
    _bgView.layer.cornerRadius = 10;
    _bgView.layer.masksToBounds = true;
    
    // 输入框内容缩进
    self.mailInputView.delegate = self;
    self.mailInputView.edgeInsets = UIEdgeInsetsMake(0, 10, 0, 10);
//    // 输入框左边是mail图标
//    self.mailInputView.iconImage = [UIImage imageNamed:@"op_icon_mail"];
    
    // 输入框内容缩进
    self.passwordInputField.delegate = self;
    self.passwordInputField.edgeInsets = UIEdgeInsetsMake(0, 10, 0, 10);
//    // 输入框左边是password图标
//    self.passwordInputField.iconImage = [UIImage imageNamed:@"op_icon_password"];
    self.passwordInputField.autocapitalizationType = UITextAutocapitalizationTypeNone;
    self.passwordInputField.secureTextEntry = YES;
    showPassword = NO;
    self.passwordInputField.returnKeyType = UIReturnKeyGo;//变为完成按钮
    
    //根据服务器配置的注册方式，如果包含邮箱注册，则显示邮箱注册按钮
    if ([OpenSDK_DataManager getInstance].supportRegisterTypes == nil || ![[OpenSDK_DataManager getInstance].supportRegisterTypes containsObject:OpenSDK_S_ACCOUNT]) {
        self.registerMsgView.hidden = YES;
        self.registerBtn.hidden = YES;
    }
    
    if (self.navigationController.viewControllers.count > 1) {
        // 从其他界面跳转过来
        self.backBtn.hidden = NO;
        self.closeBtn.hidden = YES;
    } else {
        // 本身是第一个界面
        self.backBtn.hidden = YES;
        self.closeBtn.hidden = NO;
    }
    
    //其他登录方式的显示
    [[OpenSDK_UIManager getInstance] handleOtherLoginTypesWithButton:self.otherLoginBtn curLoginType:OpenSDK_S_ACCOUNT];
}


- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    // 设置对勾按钮状态
    [_userAgreementView.agreeButton setSelected:[OpenSDK_DataManager getInstance].contranctChecked];
    
    [[OPKTracking shared] pageView:OPKPageLoginPassword];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

// 用户协议相关检查
- (BOOL)contranctChecked {
    if ([OpenSDK_DataManager getInstance].showContranct == NO) {
        return YES;
    }
    // 是否已经同意用户协议
    if (_userAgreementView.agreeButton.isSelected == NO) {
        [[[OpenSDK_iToast makeText:@"请先同意相关政策条款再登录"] setDuration:2000] show];
        return NO;
    }
    return YES;
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

#pragma mark - textField
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [self didClickLoginBtn:nil];
    return YES;
}

-(void)textFieldDidBeginEditing:(UITextField *)textField {
    [super textFieldDidBeginEditing:textField];
}

-(void)textFieldDidEndEditing:(UITextField *)textField {
    [super textFieldDidEndEditing:textField];
}

#pragma mark - btn callback
- (IBAction)didClickBackBtn:(id)sender {
    [self.navigationController popViewControllerAnimated:NO];
}

- (IBAction)didClickCloseBtn:(id)sender {
    //    [self dismissViewControllerAnimated:NO completion:nil];
    [[OpenSDK_UIManager getInstance] closeUI];
    [[OpenSDK_LoginManager getInstance] sendLoginCacelEvent];
}

- (IBAction)didClickPasswordBtn:(id)sender {
    if (showPassword) {
        showPassword = NO;
        NSString *tempPwdStr = self.passwordInputField.text;
        self.passwordInputField.text = @""; // 这句代码可以防止切换的时候光标偏移
        self.passwordInputField.secureTextEntry = YES;
        self.passwordInputField.text = tempPwdStr;
        [self.passwordVisibleBtn setImage:[UIImage imageNamed:@"op_pw_off"] forState:UIControlStateNormal];
    } else {
        showPassword = YES;
        NSString *tempPwdStr = self.passwordInputField.text;
        self.passwordInputField.text = @""; // 这句代码可以防止切换的时候光标偏移
        self.passwordInputField.secureTextEntry = NO;
        self.passwordInputField.text = tempPwdStr;
        [self.passwordVisibleBtn setImage:[UIImage imageNamed:@"op_pw_on"] forState:UIControlStateNormal];
    }
}

- (IBAction)didClickLoginBtn:(id)sender {
    
    //收起键盘
    [self didHideKeyboard:sender];
    
    // 统计
    [[OPKTracking shared] event:OPKEventLoginPasswordNext];
    
    // 是否已经同意用户协议
    if ([self contranctChecked] == NO) {
        return;
    }
    
    NSString *mail = self.mailInputView.text;
    if (mail == nil || mail.length == 0) {
        [[[OpenSDK_iToast makeText:@"抱歉，请输入邮箱"] setDuration:2000] show];
        return;
    }
    
    if (![self validateEMail:mail] && ![self validateMobile:mail]) {
        [[[OpenSDK_iToast makeText:@"抱歉，请输入正确账号"] setDuration:2000] show];
        return;
    }
    
    NSString *password = self.passwordInputField.text;
    if (password == nil || password.length == 0) {
        [[[OpenSDK_iToast makeText:@"抱歉，请输入密码"] setDuration:2000] show];
        return;
    }
    
    // 先弹出loading框
    UIStoryboard *loginStoryboard = [UIStoryboard storyboardWithName:@"LoginMain" bundle:nil];
    OpenSDK_LoginLoadingView *vc = (OpenSDK_LoginLoadingView *) [loginStoryboard instantiateViewControllerWithIdentifier:@"OpenSDK_LoginLoadingView"];
    [self.navigationController pushViewController:vc animated:NO];
    
    if ([self validateEMail:mail]) {
        vc.accoutnName = [self secureEMailWith:mail];
        // 再调用登录接口
        [[OpenSDK_LoginManager getInstance] loginWithMail:mail password:password delegate:^(BOOL result, OpenSDK_AccountRecord *account, long errorNo, NSString *err) {
            if (!result) {
                // 登录失败
                [[[OpenSDK_iToast makeText:err] setDuration:2000] show];
            }
            [vc loginResultCallback:result account:account];
        }];
    } else {
        vc.accoutnName = [self securePhoneNumberWith:mail];
        [[OpenSDK_LoginManager getInstance] loginWithMobile:mail password:password delegate:^(BOOL result, OpenSDK_AccountRecord *account, long errorNo, NSString *err) {
            if (!result) {
                // 登录失败
                [[[OpenSDK_iToast makeText:err] setDuration:2000] show];
            }
            [vc loginResultCallback:result account:account];
        }];
    }
    
    
}


- (NSString *)securePhoneNumberWith:(NSString *)number {
    if (number == nil) {
        return @"";
    }
    if (number.length <= 6) {
        return number;
    }
    NSInteger index = floor((number.length - 4) / 2.0);
    NSString *result = [number stringByReplacingCharactersInRange:NSMakeRange(index, 4) withString:@"****"];
    return result;
}

- (NSString *)secureEMailWith:(NSString *)mail {
    if (mail == nil) {
        return @"";
    }
    if (![mail containsString:@"@"]) {
        return mail;
    }
    
    NSInteger atIndex = [mail rangeOfString:@"@"].location;
    NSInteger xCount = floor(atIndex / 2.0);
    NSString *x = @"";
    for (int i = 0; i < xCount; i++) {
        x = [x stringByAppendingString:@"*"];
    }
    NSString *result = [mail stringByReplacingCharactersInRange:NSMakeRange(xCount, xCount) withString:x];
    return result;
}


- (IBAction)didClickRegisterBtn:(id)sender {
    // 收起键盘
    [self didHideKeyboard:sender];
    // 跳转到邮箱注册界面
    [[OpenSDK_UIManager getInstance] showNextUIWithStoryBoard:@"LoginMain" withVCId:@"OpenSDK_RegisterMailView"];
}

- (IBAction)didClickFindPasswordBtn:(id)sender {
    // 收起键盘
    [self didHideKeyboard:sender];
    // 跳转到重置密码界面
    [[OpenSDK_UIManager getInstance] showNextUIWithStoryBoard:@"LoginMain" withVCId:@"OpenSDK_ResetPasswordView"];
}

- (IBAction)loginDyMobile:(UIButton *)sender {
    //收起键盘
    [self didHideKeyboard:sender];
    
    // 跳转到验证码登录界面
    [[OpenSDK_UIManager getInstance] showViewControllerWithSBId:@"LoginMain" vcid:@"OpenSDK_LoginMobileView"];
}
- (IBAction)loginMore:(UIButton *)sender {
    //收起键盘
    [self didHideKeyboard:sender];
    
    BOOL contranctChecked = _userAgreementView.agreeButton.isSelected == NO ? NO : YES;
    [[OpenSDK_UIManager getInstance] handleOtherLoginMethodWithCurLoginType:OpenSDK_S_ACCOUNT contranctChecked:contranctChecked];
    
//    [[OPKTracking shared] event:OPKEventLoginOther];
//
//    // 跳转到更多登录界面
//    [[OpenSDK_UIManager getInstance] showViewControllerWithSBId:@"LoginMain" vcid:@"OpenSDK_LoginMoreView"];
}
- (IBAction)forgotPasswordAction:(UIButton *)sender {
    [self forgotPassword];
}

- (void)forgotPassword {
    OPKWebViewController *webViewController = [[OPKWebViewController alloc] init];
//        webViewController.url = [OpenSDK_DataManager getInstance].userCenterUrl;
    
    webViewController.url = [NSString stringWithFormat:@"%@/#/forgotpassword?from=client", [OpenSDK_DataManager getInstance].userCenterUrl];
//    webViewController.url = @"http://192.168.44:8080/#/forgotpassword?from=client";
    UINavigationController *navController = [[UINavigationController alloc]initWithRootViewController:webViewController];
    [navController setNavigationBarHidden:YES];
    navController.modalPresentationStyle = UIModalPresentationOverFullScreen;
    [self presentViewController:navController animated:YES completion:nil];
}

- (BOOL)validateEMail:(NSString*)email{
    NSString*regex =@"^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]+)+$";
    NSPredicate* emailPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    return[emailPredicate evaluateWithObject:email];
    
}

- (BOOL) validateMobile:(NSString *)mobile {
    NSString *phoneRegex = @"^(1[3-9][0-9])\\d{8}$";
    NSPredicate *phonePredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",phoneRegex];
    return [phonePredicate evaluateWithObject:mobile];
}

@end
